package microcredit.model.bo;

import java.sql.SQLIntegrityConstraintViolationException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;

import microcredit.db.Factory;

public abstract class BOBase  {

	protected EntityManagerFactory factory = Factory.getFactory();
	protected EntityManager manager;
	protected boolean connected = false;
	protected boolean unitTest = false;
	
	public void connectSession(BOBase base) {
		if (this.manager != null) {
			throw new IllegalStateException("Another manager already opened!");
		}
		this.manager = base.manager;
		this.connected = true;
	}
	
	public void open() {
		if (connected) {
			return;
		}
		manager = factory.createEntityManager();
		manager.getTransaction().begin();
	}
	
	public void flush() {
		if (connected) {
			return;
		}
		manager.flush();
	}
	
	public void commit() {
		if (connected) {
			return;
		}
		manager.flush();
		if (unitTest) {
			manager.getTransaction().rollback();
		} else {
			manager.getTransaction().commit();
		}
		
		manager.getTransaction().begin();
	}
	
	public void close() {
		if (connected) {
			return;
		}
		if (manager.getTransaction().isActive()) {
			manager.getTransaction().rollback();
		}
		manager.close();
		manager = null;
	}
	
	protected static boolean nullOrEmpty(String s) {
		if (s == null || s.length() == 0) {
			return true;
		}
		return false;
	}
	
	protected static boolean handleIntegrity(PersistenceException e) {
		Throwable t = e;
		while ((t = t.getCause()) != null) {
			if (t instanceof SQLIntegrityConstraintViolationException) {
				return true;
			}
		}
		throw e;
	}
	
}
